<template>
  <view>
    <view class="wrapper" v-if="!loading && pageError == false">
      <view class="pay_box">
        <view class="name">{{config.shop_name}}</view>
        <view class="pay_row">
          <view class="yang">￥</view>
          <input type="text" placeholder="0.00" v-model="amount" disabled="true" />
          <image :src="statics + 'pay_close.png'" class="pay_close" v-if="amount > 0" @click="onClearAmount"></image>
        </view>
        <view class="man_row">
          <view class="man_left">
            <view class="man_img">
              <image class="" :src="user ? user.avatar : statics + 'user.png'" mode="aspectFill"></image>
            </view>
            <view class="man_info" v-if="!user.is_active" @click="showUserActiveDecWindow = true">
              <view class="man_name">未激活用户</view>
              <image class="" :src="statics + 'wenhao.png'"></image>
            </view>
            <view class="man_info" v-else>
              <view class="man_name">{{user.nickname}}</view>
            </view>
          </view>
          <view class="band" @click="showLoginWindow = true" v-if="!user.is_active">
            去同步
            <image class="" :src="statics + 'blue_arrow.png'"></image>
          </view>
          <view class="band" v-else>已同步</view>
        </view>
      </view>

      <!-- 抵扣 -->
      <view class="grid_row" v-if="user">
        <view class="off">可用{{redPacketAmount}}个红包抵扣{{redPacketAmount}}元</view>
        <switch class="" :checked="false" type="switch" @change="onUseRedPacket"></switch>
      </view>

      <!-- 余额支付 -->
      <view class="grid_row" @click="onSelected('wallet')" v-if="user">
        <view class="yue">
          <image class="" :src="statics + 'wallet_select.png'"></image>
          <view class="yue_name">余额支付（¥{{user.amount || 0}}）</view>
        </view>
        <image class="wenhao_icon" :src="statics + (selected == 'wallet' ? 'gou.png' : 'none.png')"></image>
      </view>

      <!-- 支付宝支付 -->
      <view class="grid_row" @click="onSelected('alipay')">
        <view class="zhifubao">
          <image class="" :src="statics + 'zfb.png'"></image>
          <view class="zhifubao_dec">支付宝</view>
        </view>
        <image class="wenhao_icon" :src="statics + (selected == 'alipay' ? 'gou.png' : 'none.png')"></image>
      </view>

      <!-- 统计 -->
      <view class="total_row">
        实付金额：<text>￥{{payAmount}}</text>
      </view>
    </view>
    <u-loading-page :loading="loading"></u-loading-page>
    <u-empty v-if="pageError" mode="page" :icon="statics + '404.png'" text="页面不存在,请使用支付宝扫码打开!">
    </u-empty>

    <!-- 同步弹窗 -->
    <view class="mask" v-if="showLoginWindow || showUserActiveDecWindow"
      @click="showUserActiveDecWindow = false; showLoginWindow = false"></view>

    <view class="popup" v-if="showLoginWindow">
      <view class="popup_top">
        <view class="popup_name">同步用户信息</view>
        <view class="popup_dec">同步前请到微信扫码验证</view>
      </view>
      <view class="entry_box">
        <view class="entry_row">
          <image class="wenhao_icon" :src="statics + 'tphone.png'"></image>
          <input type="text" placeholder="请输入手机号码" v-model="formData.phone" />
        </view>
        <view class="entry_row">
          <image class="wenhao_icon" :src="statics + 'lock.png'"></image>
          <input type="text" placeholder="请输入验证码" v-model="formData.captcha.code" />
          <u-code :seconds="seconds" ref="uCode" @change="captchaChange"></u-code>
          <view class="code_btn" @tap="sendCaptcha">{{tips}}</view>
        </view>
      </view>
      <view class="red_btn" @click="active">立即激活</view>
    </view>

    <!-- 激活说明 -->
    <view class="popup" v-if="showUserActiveDecWindow">
      <view class="popup_top">
        <view class="popup_name">未激活用户</view>
      </view>
      <view class="popup_content">
        <rich-text class="" :nodes="config.explain">

        </rich-text>
      </view>
      <view class="red_btn" @click="showUserActiveDecWindow = false">我知道了</view>
    </view>


    <!-- 键盘 -->
    <view class="keyboard" v-if="!loading && pageError == false">
      <view class="keyboard_left" @click.stop="onKeyPress">
        <view class="item" data-key="1">1</view>
        <view class="item" data-key="2">2</view>
        <view class="item" data-key="3">3</view>
        <view class="item" data-key="4">4</view>
        <view class="item" data-key="5">5</view>
        <view class="item" data-key="6">6</view>
        <view class="item" data-key="7">7</view>
        <view class="item" data-key="8">8</view>
        <view class="item" data-key="9">9</view>
        <view class="zero" data-key="0">0</view>
        <view class="dot" data-key=".">.</view>
      </view>
      <view class="keyboard_right">
        <view class="del">
          <image :src="statics + 'del.png'" @click="onDeleteKeyPress"></image>
        </view>
        <view class="btn" :class="{on:amount > 0}" @click="onPayKeyPress">付款</view>
      </view>
    </view>
  </view>
</template>

<script>
  import Request from "@/utils/request.js";
  import alipay from "@/utils/alipay.js"

  import {
    getAccessToken,
    setAccessToken
  } from '@/utils/token'
  export default {
    data() {
      return {
        pageError: false,
        loading: true,
        statics: getApp().globalData.staticUrl,
        config: {
          use_red_packet: 0,
          merchant_id: 0,
          shop_id: 0,
        },
        amount: '',
        payAmount: 0.00,
        redPacketAmount: 0,
        useRedPacket: false,
        user: {
          is_active: false
        },
        showLoginWindow: false,
        showUserActiveDecWindow: false,
        selected: 'alipay',
        formData: {
          phone: '',
          captcha: {
            id: 0,
            code: ''
          }
        },
        seconds: 60,
        tips: "",
        inProgress: false
      };
    },
    mounted() {
      console.log('mounted')
    },
    onLoad(options) {
      console.log('onLoad')
      console.log(options)
      if (!options.mid || !options.sid) {
        return this.error(10000)
      } else {
        if (!alipay.isAlipay) {
          return this.error(10001)
        }

        alipay.hideOptionButton()
        this.config.merchant_id = options.mid;
        this.config.shop_id = options.sid;

        this.init()
      }
    },
    onShow() {

    },
    methods: {
      init() {
        let merchantId = this.config.merchant_id
        let shopId = this.config.shop_id
        Request.get(`/merchants/${merchantId}/shops/${shopId}/config`).then(res => {
          this.config = res.data
          this.login()
          /* uni.setNavigationBarTitle({
            title: res.data.shop_name
          }); */
        })
      },
      captchaChange(text) {
        this.tips = text;
      },
      sendCaptcha() {
        console.log('sendCaptcha')
        if (!this.phoneValidation()) {
          return false;
        }

        if (this.$refs.uCode.canGetCode) {
          uni.showLoading({
            title: '正在获取验证码'
          })
          Request.post('/captcha', {
            data: {
              phone: this.formData.phone
            }
          }).then(res => {
            this.formData.captcha.id = res.data.id

            uni.hideLoading();
            // 这里此提示会被this.start()方法中的提示覆盖
            uni.$u.toast('验证码已发送', 3000);
            // 通知验证码组件内部开始倒计时
            this.$refs.uCode.start();

          }).catch((res) => {
            uni.showToast({
              icon: "none",
              title: res.data.message
            })
          })
        } else {
          uni.$u.toast('倒计时结束后再发送');
        }
      },
      login() {
        let _this = this
        alipay.getAuthCode({
          appId: '2021003136647126',
          scopes: ['auth_base'],
          showErrorTip: false
        }, function(res) {
          Request.post('/auth', {
            data: {
              auth_code: res.authCode,
              merchant_id: _this.config.merchant_id
            }
          }).then(res => {
            _this.storageToken(res.data)
            _this.loaded()
          }).catch(res => {
            _this.loaded(true)
          })
        });
      },
      active() {
        console.log('active')
        if (this.inProgress) {
          return;
        }
        if (this.formValidation()) {
          this.inProgress = true;
          uni.showLoading({
            title: '正在同步'
          })
          Request.post('/active', {
            data: Object.assign({
              merchant_id: this.config.merchant_id,
              shop_id: this.config.shop_id
            }, this.formData)
          }).then(res => {
            console.log(res)
            this.inProgress = false;
            this.showLoginWindow = false
            uni.hideLoading();
            if (!res.data.user) {
              return uni.showToast({
                icon: "none",
                title: '同步失败，用户不存在'
              })
            }
            this.storageToken(res.data)
            uni.showToast({
              icon: "none",
              title: '同步成功'
            })
          }).catch(() => {
            this.inProgress = false;
            uni.hideLoading();
          })
        }
      },
      onKeyPress(e) {
        let key = e.target.dataset.key;
        switch (String(key)) {
          //小数点
          case '.':
            this.onDotKeyPress();
            break;
          default:
            this.onNumberKeyPress(key);
        }
      },
      onDotKeyPress() {
        //如果包含小数点，直接返回
        if (this.amount.indexOf('.') > -1) return false;
        //如果小数点是第一位，补0
        if (!this.amount.length) {
          this.amount = '0.';
        } else {
          //如果不是，添加一个小数点
          this.amount = this.amount + '.';
        }
        this.calcPaidAmount()
      },
      onDeleteKeyPress() {
        let amount = this.amount;
        //如果没有输入，直接返回
        if (!amount.length) return false;
        //否则删除最后一个
        this.amount = amount.substring(0, amount.length - 1);
        this.calcPaidAmount()
      },
      onNumberKeyPress(num) {
        let amount = this.amount;
        if (amount > 100000) {
          uni.showToast({
            icon: "none",
            title: "支付金额不能超过10万"
          })
          return;
        }

        //如果有小数点且小数点位数不小于2
        if (amount.indexOf('.') > -1 && amount.substring(amount.indexOf('.') + 1).length < 2) {
          this.amount = amount + num;
        }

        //没有小数点
        if (!(amount.indexOf('.') > -1)) {
          //如果第一位是0，只能输入小数点
          if (num == 0 && amount.length == 0) {
            this.amount = '0.';
          } else {
            if (amount.length && Number(amount.charAt(0)) === 0) return;
            this.amount = amount + num;
          }
        }

        this.calcPaidAmount()
      },
      onClearAmount() {
        this.amount = '';
        this.payAmount = 0;
      },
      onPayKeyPress() {
        if (this.amount < 0.01) {
          return;
        }
        if (this.inProgress) {
          return;
        }
        this.inProgress = true;
        uni.showLoading()
        let redPacketAmount = this.redPacketAmount
        if (!this.useRedPacket) {
          redPacketAmount = 0
        }
        Request.post('/pay', {
          data: {
            amount: this.amount,
            pay_type: this.selected,
            red_packet: redPacketAmount,
            shop_id: this.config.shop_id,
            merchant_id: this.config.merchant_id
          }
        }).then(res => {
          this.inProgress = false;
          uni.hideLoading()
          let data = res.data
          if (data.channel == 'wallet' && data.status == 10) {
            uni.redirectTo({
              url: './result?pay_no=' + data.pay_no
            })
          } else {
            alipay.tradePay({
              tradeNO: data.parameters.reserved_transaction_id
            }, function(res) {
              if (res.resultCode == 9000) {
                uni.redirectTo({
                  url: './result?pay_no=' + data.pay_no
                })
              } else {
                let message = '订单支付失败';
                if (res.resultCode == 8000) {
                  message = '正在处理中';
                } else if (res.resultCode == 6001) {
                  message = '用户中途取消';
                } else if (res.resultCode == 6002) {
                  message = '网络连接出错';
                } else if (res.resultCode == 99) {
                  message = '用户点击忘记密码导致快捷界面退出(only iOS)';
                }
                uni.showToast({
                  icon: "none",
                  title: message
                })
              }
            })
          }
        }).catch(res => {
          this.inProgress = false;
        })
      },
      //选择支付方式
      onSelected(mode) {
        if (mode == 'wallet' && this.user.amount == 0) {
          uni.showToast({
            icon: "none",
            title: '余额为0'
          })
          return;
        }
        this.selected = mode;
      },
      //使用红包
      onUseRedPacket(e) {
        this.useRedPacket = e.detail.value
        // if (!this.useRedPacket) {
        //   this.redPacketAmount = 0
        // }
        this.calcPaidAmount()
      },
      //计算红包金额
      calcRedPacketAmount() {
        this.redPacketAmount = 0;
        let userRedPacketAmount = this.user.red_packet
        if (userRedPacketAmount > 0) {
          let config = this.config
          let maxUseRedPacketAmount = userRedPacketAmount;
          if (config.use_red_packet > 0) {
            maxUseRedPacketAmount = config.use_red_packet * 0.01 * this.amount
            maxUseRedPacketAmount = Number(maxUseRedPacketAmount).toFixed(2);
          }
          this.redPacketAmount = Math.min(userRedPacketAmount, maxUseRedPacketAmount);
        }

        return this.redPacketAmount;
      },
      //计算支付金额
      calcPaidAmount() {
        let amount = this.amount;
        //未输入
        if (!amount.length) {
          this.payAmount = 0;
          return false;
        }

        //将 8. 这种转换成 8.00
        if (amount.indexOf('.') > -1 && amount.indexOf('.') == (amount.length - 1)) {
          amount = Number(amount.substring(0, amount.length - 1)).toFixed(2);
        }

        let redPacketAmount = this.calcRedPacketAmount()
        if (this.useRedPacket) {
          amount = amount - redPacketAmount
        }
        if (amount < 0) {
          amount = 0;
        }
        //保留两位
        this.payAmount = Number(amount).toFixed(2);
      },
      phoneValidation() {
        if (this.formData.phone.length == 0) {
          uni.showToast({
            icon: "none",
            title: "请输入手机号"
          })
          return false;
        }
        return true;
      },
      storageToken(data) {
        this.user = data.user
        if (!this.user.avatar) {
          this.user.avatar = this.statics + 'user.png'
        }
        setAccessToken(data.access_token);
      },
      loaded(pageError = false) {
        this.loading = false;
        this.pageError = pageError
      },
      error(code) {
        return uni.navigateTo({
          url: `/pages/index/error?code=${code}`
        })
      },
      //表单验证
      formValidation() {
        if (!this.phoneValidation()) {
          return false;
        }

        let pattern = new RegExp("^1[345789][0-9]{9}$", 'i');
        if (!pattern.test(this.formData.phone)) {
          uni.showToast({
            icon: "none",
            title: "请输入正确的手机号"
          })
          return false;
        }

        if (this.formData.captcha.code.length == 0) {
          uni.showToast({
            icon: "none",
            title: "请输入验证码"
          })
          return false;
        }

        return true;
      }
    },
  }
</script>

<style lang="scss">
  .wrapper {
    padding: 24rpx;
  }

  .user {
    padding: 20rpx 0;
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
  }

  .user_img {
    width: 88rpx;
    height: 88rpx;
    margin-right: 20rpx;
    border-radius: 12rpx;
    overflow: hidden;
    background-color: #fff;
  }

  .user_img image {
    height: 88rpx;
  }

  .user_name {
    font-size: 28rpx;
    color: #333;
  }

  .pay_box {
    margin-bottom: 20rpx;
    padding: 0 20rpx;
    border-radius: 20rpx;
    background-color: #fff;
  }

  .pay_box .name {
    padding: 30rpx 0;
    margin-bottom: 30rpx;
    font-size: 28rpx;
    color: #333;
  }

  .pay_row {
    display: flex;
    align-items: center;
    height: 100rpx;
    border-bottom: 1PX #e6e6e6 solid;
    position: relative;
  }

  .yang {
    font-size: 72rpx;
    font-weight: bold;
    color: #333;
  }

  .pay_row input {
    flex: 1;
    height: 72rpx;
    font-size: 72rpx;
    font-weight: bold;
  }

  .pay_close {
    width: 48rpx;
    height: 48rpx;
    position: absolute;
    top: 50%;
    right: 0;
    transform: translateY(-50%);
  }

  .backup input {
    width: 100%;
    height: 100rpx;
    font-size: 26rpx;
    color: #666;
  }

  .keyboard {
    width: 100%;
    display: flex;
    padding: 0;
    padding-bottom: calc(env(safe-area-inset-bottom) / 2);
    background-color: #fff;
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 5;
  }

  .keyboard_left {
    width: 560rpx;
    display: flex;
    flex-wrap: wrap;
  }

  .keyboard .item {
    width: 33.3333333%;
    height: 110rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    border-right: 1PX #F9F9F9 solid;
    border-bottom: 1PX #F9F9F9 solid;
    font-size: 50rpx;
    color: #333;
  }

  .keyboard .item:active {
    background-color: #e7e6eb;
  }

  .keyboard .zero {
    width: 66.6666666%;
    height: 110rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    border-right: 1PX #F9F9F9 solid;
    border-bottom: 1PX #F9F9F9 solid;
    font-size: 50rpx;
    color: #333;
  }

  .keyboard .zero:active {
    background-color: #e7e6eb;
  }

  .keyboard .dot {
    width: 33.3333333%;
    height: 110rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    border-right: 1PX #F9F9F9 solid;
    border-bottom: 1PX #F9F9F9 solid;
    font-size: 50rpx;
    color: #333;
  }

  .keyboard .dot:active {
    background-color: #e7e6eb;
  }

  .keyboard_right {
    width: 190rpx;
  }

  .del {
    height: 110rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .del:active {
    background-color: #e7e6eb;
  }

  .del image {
    width: 50rpx;
    height: 50rpx;
  }

  .keyboard .btn {
    width: 100%;
    height: 330rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #F2BBBC;
    font-size: 32rpx;
    color: #fff;
  }

  .keyboard .btn.on {
    background-color: #D32224;
  }

  .man_row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 100rpx;
  }

  .man_row .man_left {
    display: flex;
    align-items: center;
  }

  .man_img {
    width: 48rpx;
    height: 48rpx;
    margin-right: 20rpx;
    border-radius: 50%;
    overflow: hidden;
  }

  .man_img image {
    height: 48rpx;
  }

  .man_info {
    display: flex;
    align-items: center;
  }

  .man_info .man_name {
    margin-right: 20rpx;
    font-size: 30rpx;
    color: #999;
  }

  .man_info image {
    width: 48rpx;
    height: 48rpx;
  }

  .band {
    display: flex;
    align-items: center;
    font-size: 30rpx;
    color: #027AFF;
  }

  .band image {
    width: 16rpx;
    height: 28rpx;
    margin-left: 10rpx;
  }

  .grid_row {
    padding-left: 30rpx;
    padding-right: 20rpx;
    margin-bottom: 20rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 100rpx;
    border-radius: 16rpx;
    background-color: #fff;
  }

  .off {
    font-size: 30rpx;
    color: #333;
  }

  .yue {
    display: flex;
    align-items: center;
  }

  .yue image {
    width: 48rpx;
    height: 48rpx;
    margin-right: 20rpx;
  }

  .yue_name {
    font-size: 30rpx;
    color: #333;
  }

  .wenhao_icon {
    width: 48rpx;
    height: 48rpx;
  }

  .zhifubao {
    display: flex;
    align-items: center;
  }

  .zhifubao image {
    width: 48rpx;
    height: 48rpx;
    margin-right: 20rpx;
  }

  .zhifubao_dec {
    font-size: 30rpx;
    color: #333;
  }

  .total_row {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    font-size: 30rpx;
    color: #333;
  }

  .total_row text {
    font-size: 48rpx;
    color: #EE2720;
  }

  .popup {
    width: 640rpx;
    padding: 40rpx;
    border-radius: 16rpx;
    background-color: #fff;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 50;
  }

  .popup_top {
    margin-bottom: 30rpx;
    text-align: center;
  }

  .popup_name {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }

  .popup_dec {
    font-size: 30rpx;
    color: #999;
  }

  .entry_box {
    margin-bottom: 100rpx;
  }

  .entry_row {
    margin-bottom: 20rpx;
    height: 80rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1PX #e6e6e6 solid;
  }

  .entry_row input {
    margin-left: 15rpx;
    flex: 1;
    font-size: 30rpx;
  }

  .code_btn {
    font-size: 24rpx;
    color: #027AFF;
  }

  .red_btn {
    width: 100%;
    height: 100rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 50rpx;
    background: linear-gradient(90deg, #FF7350, #FF2E2E);
    box-shadow: 0 10rpx 10rpx rgba(255, 46, 46, .1);
    font-weight: bold;
    font-size: 36rpx;
    color: #fff;
  }

  .popup_content {
    margin-bottom: 100rpx;
    font-size: 30rpx;
    color: #8E8E8E;
  }
</style>
